<template>
  <div id="home-main-user">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 搜索与添加用户实现 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList">
            <template #append>
              <el-button
                icon="el-icon-search"
                @click="getUserList"/>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="isShowAddDialog = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格实现 -->
      <el-table
        :data="userInfo"
        style="width: 100%"
        border
        stripe>
        <el-table-column min-width="200" type="index"></el-table-column>
        <el-table-column min-width="80" prop="username" label="姓名"></el-table-column>
        <el-table-column min-width="140" prop="email" label="邮箱"></el-table-column>
        <el-table-column min-width="110" prop="mobile" label="电话"></el-table-column>
        <el-table-column min-width="100" prop="role_name" label="角色"></el-table-column>
        <el-table-column min-width="60" label="状态" v-slot:default="scope">
          <!-- 控制状态 -->
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            @change="changeUserState(scope.row)">
          </el-switch>
            <!-- {{ scope.row }} -->
        </el-table-column>
        <el-table-column
          min-width="180"
          label="操作"
          v-slot:default="scope">
          <!-- 编辑按钮 -->
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="openEditDialog(scope.row)"/>
          <!-- 删除按钮 -->
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="deleteUser(scope.row.id)"/>
          <!-- 分配权限按钮 -->
          <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
            <el-button
              size="mini"
              type="info"
              icon="el-icon-setting"
              @click="openSetRolesDialog(scope.row)"/>
          </el-tooltip>
        </el-table-column>
      </el-table>
      <!-- 分页实现 -->
       <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 4, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalUser">
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="isShowAddDialog"
      width="50%"
      @close="closeAdd">
      <el-form
        :model="addUserForm"
        :rules="fromRules"
         ref="addUserForm"
         label-width="65px"
         :label-position="'left'">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"/>
        </el-form-item>
        <el-form-item label="密 码" prop="password">
          <el-input type="password" v-model="addUserForm.password"/>
        </el-form-item>
        <el-form-item label="邮 箱" prop="email">
          <el-input v-model="addUserForm.email"/>
        </el-form-item>
        <el-form-item label="手 机" prop="mobile">
          <el-input v-model="addUserForm.mobile"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowAddDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑窗口dialog -->
    <el-dialog
      title="提示"
      :visible.sync="isShowEditdialog"
      width="50%"
      @cloas="closeEditDialog">
      <el-form
        :model="editUserForm"
        :rules="fromRules"
        :label-position="'left'"
        label-width="65px"
        ref="editFormRef">
        <el-form-item label="用户名">
          <el-input
            disabled
            v-model="editUserForm.username"
            />
        </el-form-item>
        <el-form-item label="邮 箱" prop="email">
          <el-input v-model="editUserForm.email"/>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserForm.mobile"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isShowEditdialog = false">取 消</el-button>
          <el-button type="primary" @click="editUserConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色窗口 -->
    <el-dialog
      title="分配角色"
      :visible.sync="isShowSetRolesDialog"
      @close="closeSetRoleDialog"
      width="50%">
      <el-form
        :model="setRolesForm"
        label-width="85px"
        :label-position="'left'">
        <el-form-item label="用户名">
          <el-input
            v-model="setRolesForm.username"
            disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="当前角色">
          <el-input
            v-model="setRolesForm.role_name"
            disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="请选择角色">
          <el-select
            v-model="setRolesForm.selectRoleId"
            placeholder="请选择">
            <el-option
              v-for="(value, index) in rolesList"
              :key="value.roleName + index"
              :label="value.roleName"
              :value="value.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isShowSetRolesDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmChangeUserRole">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'HomeMainUser',
  data () {
    // 手机rule
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (regMobile.test(value)) {
        // 合法的手机号
        return callback()
      }
      callback(new Error('请输入正确的手机号'))
    }
    // 邮箱rule
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱'))
    }
    return {
      // 添加用户的规则
      fromRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3~10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '用户名的长度在6~15个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, message: '请输入正确的邮箱', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 获取用户列表的数据
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 8
      },
      // table中用到的数据
      userInfo: [],
      // 服务器返回来总共的用户数量
      totalUser: 0,
      // 控制添加用户的dialog是否弹出
      isShowAddDialog: false,
      // 控制edit的dialog是否弹出
      isShowEditdialog: false,
      // 添加新用户的信息
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 编辑用户的信息
      editUserForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 是否展示分配角色的dialog
      isShowSetRolesDialog: false,
      // 分配角色对话框的信息
      setRolesForm: {
        // 记录id
        id: '',
        username: '',
        role_name: '',
        // 当前选中的角色
        selectRoleId: '',
        // 以前的角色
        oldRole: ''
      },
      // 角色列表
      rolesList: []
    }
  },
  created () {
    // 初始化获得用户数据
    this.getUserList()
  },
  methods: {
    // 1. 初次获取/更新用户列表
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败!')
      this.userInfo = res.data.users
      this.totalUser = res.data.total
    },
    // 2. 更改每页用户数量并更新用户列表
    handleSizeChange (eachPageNum) {
      this.queryInfo.pagesize = eachPageNum
      this.getUserList()
      // console.log(num)
    },
    // 3. 更换页码并显示用户
    handleCurrentChange (pageNum) {
      this.queryInfo.pagenum = pageNum
      this.getUserList()
    },
    // 4. 修改用户状态
    async changeUserState (user) {
      // console.log(user)
      const { data: res } = await this.$http.put(`/users/${user.id}/state/${user.mg_state}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        user.mg_state = !user.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 5. 关闭添加用户面板
    closeAdd () {
      console.log(111)
      this.$refs.addUserForm.resetFields()
    },
    // 6. 点击确定新增用户
    confirmAddUser () {
      this.$refs.addUserForm.validate(async valid => {
        // 为false的时候终止
        if (!valid) return false
        // 不为false可以发送请求
        const { data: res } = await this.$http.post('/users', this.addUserForm)
        if (res.meta.status !== 201 && res.meta.status === 400) {
          return this.$message.error('用户名已存在')
        } else if (res.meta.status === 201) {
          this.$message.success('添加用户成功!')
          // 关闭dialog并重新获取数据
          this.getUserList()
          this.isShowAddDialog = false
        }
      })
    },
    // 7. 删除用户
    async deleteUser (userId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 判断是否点击了确定
      if (confirmResult === 'cancel') {
        return this.$message.info('已取消删除')
      } else if (confirmResult === 'confirm') {
        // console.log(userId)
        const { data: res } = await this.$http.delete('/users/' + userId)
        if (res.meta.status !== 200) {
          return this.$message.error('删除用户失败.')
        } else if (res.meta.status === 200) {
          this.$message.success('删除用户成功!')
          this.getUserList()
        }
      }
    },
    // 8. 编辑用户
    openEditDialog (user) {
      this.isShowEditdialog = true
      if (user) {
        this.editUserForm.username = user.username
        this.editUserForm.email = user.email
        this.editUserForm.mobile = user.mobile
        this.editUserForm.id = user.id
      }
    },
    // 9. 处理关闭编辑dialog时的函数
    closeEditDialog () {
      this.$refs.editFormRef.resetFields()
      this.editUserForm = ''
    },
    // 10. 点击确认
    editUserConfirm () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false
        if (this.editUserForm.id) {
          const { data: { meta: { status } } } = await this.$http.put('/users/' + this.editUserForm.id, this.editUserForm)
          // console.log(res)
          if (status !== 200) {
            this.$message.error('修改用户失败.')
          } else if (status === 200) {
            this.$message.success('修改用户成功!')
            this.isShowEditdialog = false
          }
        }
      })
    },
    // 11. 点击分配角色按钮弹出dialog
    async openSetRolesDialog (user) {
      // console.log(user)
      // 初始化表单
      this.setRolesForm.id = user.id
      this.setRolesForm.username = user.username
      this.setRolesForm.role_name = user.role_name
      // 当前选中的角色
      this.setRolesForm.selectRoleId = user.role_name
      this.setRolesForm.oldRole = user.role_name
      // 获取角色表
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      // 保存角色列表
      this.rolesList = res.data
      // 打开dialog
      this.isShowSetRolesDialog = true

      console.log(res)
    },
    // 12. 确认提交修改角色表单
    async confirmChangeUserRole () {
      // 没有选择角色 return
      if (this.setRolesForm.oldRole === this.setRolesForm.selectRoleId) {
        return this.$message.info('请选择不同的角色')
      }
      const { data: res } = await this.$http.put(`/users/${this.setRolesForm.id}/role`, { rid: this.setRolesForm.selectRoleId })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('设置用户角色失败.')
      }
      this.$message.success('设置用户角色成功!')
      this.getUserList()
      // 关闭dialog
      this.isShowSetRolesDialog = false
    },
    // 13. 分配权限窗口关闭
    closeSetRoleDialog () {
      for (const key in this.setRolesForm) {
        this.setRolesForm[key] = ''
      }
      this.rolesList = []
    }
  }
}
</script>

<style scoped lang="less">
.el-breadcrumb {
  font-size: 12px;
}
.el-card {
  margin-top: 15px;
}
.el-table {
  margin-top: 15px;
}
.el-table th.gutter{
  display: table-cell!important;
}
.el-pagination {
  margin-top: 20px;
}
</style>
